package log

import (
	"log"
	"strings"

	mlog "gitee.com/yrwy/go-log"
	hlog "gitee.com/yrwy/go-log/log/log"
	"gitee.com/yrwy/go-log/log/mslog"
	mio "gitee.com/yrwy/msgo/pkg/io"
	"gitee.com/yrwy/msgo/pkg/strs"
)

var (
	_w Writer = &defaultWriter{}
)

func InitLog(logcfg string) error {
	if strs.WithSuffixFold(logcfg, ".log") {
		_w = hlog.NewWriter(logcfg, log.Llongfile|log.LstdFlags)
		return nil
	} else if mio.IsDir(logcfg) || strs.WithSuffixFold(logcfg, ".json") {
		w, err := hlog.NewJsonWriter(logcfg)
		if err != nil {
			return err
		}
		_w = w
		return nil
	} else if strings.HasSuffix(logcfg, ".yml") || strings.HasSuffix(logcfg, ".yaml") {
		w, err := mslog.NewWriter(logcfg)
		if err != nil {
			return err
		}
		_w = w
		return nil
	}
	_w = hlog.NewWriter(logcfg, log.Llongfile)
	return nil
}

func InitSLog(logcfg string) error {
	w, err := hlog.NewJsonWriter(logcfg)
	if err != nil {
		return err
	}
	_w = w
	return nil
}

func GetWriter() Writer {
	return _w
}

func LogDepth(calldepth int, lv mlog.Level, args ...any) {
	_w.LogDepth(calldepth+1, lv, args...)
}

func LogDepthf(calldepth int, lv mlog.Level, format string, args ...any) {
	_w.LogDepthf(calldepth+1, lv, format, args...)
}

func Fatal(args ...any) {
	LogDepth(2, mlog.FATAL, args...)
}

func Fatalf(format string, args ...any) {
	LogDepthf(2, mlog.FATAL, format, args...)
}

func Error(args ...any) {
	LogDepth(2, mlog.ERROR, args...)
}

func Errorf(format string, args ...any) {
	LogDepthf(2, mlog.ERROR, format, args...)
}

func Warn(args ...any) {
	LogDepth(2, mlog.WARN, args...)
}

func Warnf(format string, args ...any) {
	LogDepthf(2, mlog.WARN, format, args...)
}

func Info(args ...any) {
	LogDepth(2, mlog.INFO, args...)
}

func Infof(format string, args ...any) {
	LogDepthf(2, mlog.INFO, format, args...)
}

func Debug(args ...any) {
	LogDepth(2, mlog.DEBUG, args...)
}

func Debugf(format string, args ...any) {
	LogDepthf(2, mlog.DEBUG, format, args...)
}

func Flush() {
	_w.Close()
}
